// https://docs.pmnd.rs/
import { StoreApi, useStore, createStore } from 'zustand';
import type { IMarkerFeatureEvent, IMarkerFeatureFindEvent, ISMap, ISMapDispatchData } from '@/compnents';

interface IStoreState {
  map: ISMap | undefined;
  markerFeatureEvent: IMarkerFeatureEvent | IMarkerFeatureFindEvent | undefined;
}

type IStoreAction = {
  dispatch: (state: Partial<IStoreState>) => void;
  mapDispatch: (state: ISMapDispatchData) => void;
};

type WithSelectors<S> = S extends { getState: () => infer T } ? S & { use: { [K in keyof T]: () => T[K] } } : never;

const createSelectors = <S extends StoreApi<Record<string, any>>>(_store: S) => {
  const store = _store as WithSelectors<typeof _store>;
  store.use = {};
  for (const k of Object.keys(store.getState())) {
    (store.use as any)[k] = () => useStore(_store, (s) => s[k as keyof typeof s]);
  }

  return store;
};

const store = createStore<IStoreState & IStoreAction>((set) => ({
  map: undefined,
  markerFeatureEvent: undefined,
  dispatch: (state) => set(() => ({ ...state })),
  mapDispatch: (state) => {
    if (state.type.startsWith('markerFeature.')) {
      set(() => ({ markerFeatureEvent: state as IMarkerFeatureEvent }));
    }
  },
}));

export const useAppStore = createSelectors(store);
